<template>
    <div class="content-wrapper-view">
        <div class="content-wrapper-body">
            <div class="filter-wrapper">
                <el-form ref="filterForm" :model="listQuery" :inline="true">
                    <el-form-item prop="realName" size="medium">
                        <el-input v-model="listQuery.realName" placeholder="姓名"></el-input>
                    </el-form-item>

                    <el-form-item prop="sex" size="medium">
                        <el-select v-model="listQuery.sex" placeholder="性别" clearable style="width: 100px">
                            <el-option
                                    v-for="item in sexOptions"
                                    :key="item.key"
                                    :label="item.label"
                                    :value="item.key">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item prop="status" size="medium">
                        <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 100px">
                            <el-option
                                    v-for="item in statusOptions"
                                    :key="item.key"
                                    :label="item.label"
                                    :value="item.key">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-button type="primary" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
                    <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="handleResetFilter">重置</el-button>
                    <el-button :disabled="!authorize('system:user:add')" type="primary" size="medium" icon="el-icon-plus" @click="handleCreate">添加</el-button>
                    <el-button :disabled="!authorize('system:user:delete')" type="danger" size="medium" icon="el-icon-delete" @click="handleDelete">批量删除</el-button>
                    <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="dialogNotification">广播消息</el-button>
                </el-form>
            </div>

            <el-table
                    :data="list"
                    border fit
                    highlight-current-row
                    v-loading="listLoading"
                    element-loading-text="给我一点时间"
                    :empty-text="emptyText"
                    @selection-change="handleSelectionChange">

                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" width="55" align="center"></el-table-column>

                <el-table-column label="姓名" width="110px" align="center">
                    <template slot-scope="scope">
                        <div v-if="scope.row.superAdmin">
                            <el-tag type="danger">{{scope.row.realName}}</el-tag>
                        </div>
                        <div v-else>{{scope.row.realName}}</div>
                    </template>
                </el-table-column>

                <el-table-column label="性别" width="80px" align="center">
                    <template slot-scope="scope">
                        <el-tag type="primary" v-if="scope.row.sex === 1">男</el-tag>
                        <el-tag type="danger" v-else-if="scope.row.sex === 2">女</el-tag>
                        <el-tag type="info" v-else>未知</el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="账号" width="110px" align="center">
                    <template slot-scope="scope"> {{scope.row.account}}</template>
                </el-table-column>

                <el-table-column label="手机号码" width="130px" align="center">
                    <template slot-scope="scope"> {{scope.row.mobile}}</template>
                </el-table-column>

                <el-table-column label="邮件地址" min-width="200px" align="center" show-overflow-tooltip>
                    <template slot-scope="scope"> {{scope.row.email}}</template>
                </el-table-column>
                <el-table-column label="状态" width="80px" align="center">
                    <template slot-scope="scope">
                        <el-tag type="success" v-if="scope.row.status === true">正常</el-tag>
                        <el-tag type="danger" v-else>禁用</el-tag>
                    </template>
                </el-table-column>

                <el-table-column label="登录次数" width="100" align="center">
                    <template slot-scope="scope"> {{scope.row.loginCount}}</template>
                </el-table-column>

                <el-table-column label="最后登录IP" width="120px" min-width="" align="center">
                    <template slot-scope="scope"> {{scope.row.lastLoginIp}}</template>
                </el-table-column>

                <el-table-column label="最后登录时间" width="170px" align="center">
                    <template slot-scope="scope"> {{scope.row.lastLoginTime | parseTime }}</template>
                </el-table-column>

                <el-table-column label="创建时间" width="150px" align="center">
                    <template slot-scope="scope"> {{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}')}}</template>
                </el-table-column>

                <el-table-column label="操作" width="280" align="center">
                    <template slot-scope="scope">
                        <el-button :disabled="!authorize('system:user:add_role', scope)" size="small" type="primary" icon="edit" @click="handleAddRoleToUser(scope.row)">添加角色</el-button>
                        <el-button :disabled="!authorize('system:user:update', scope)" size="small" type="primary" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button :disabled="!authorize('system:user:delete', scope)" size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div v-if="!listLoading" class="pagination-container">
                <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="listQuery.page"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="listQuery.limit"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </div>

            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleDialogClose">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                    <el-form-item label="登录账号" prop="account">
                        <el-input v-model="form.account" style="width: 80%;"></el-input>
                    </el-form-item>

                    <el-form-item label="用户姓名" prop="realName">
                        <el-input v-model="form.realName" style="width: 80%;"></el-input>
                    </el-form-item>

                    <el-form-item label="用户性别" prop="sex">
                        <el-select v-model="form.sex" placeholder="性别" style="width: 180px">
                            <el-option
                                    v-for="item in sexOptions"
                                    :key="item.key"
                                    :label="item.label"
                                    :value="item.key"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="手机号码" prop="mobile">
                        <el-input v-model="form.mobile" style="width: 80%;"></el-input>
                    </el-form-item>

                    <el-form-item label="邮件地址" prop="email">
                        <el-input v-model="form.email" style="width: 80%;"></el-input>
                    </el-form-item>

                    <el-form-item label="账号状态" prop="status">
                        <el-radio-group v-model="form.status">
                            <el-radio :label="true">正常</el-radio>
                            <el-radio :label="false">锁定</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancel('form')">取 消</el-button>
                    <el-button v-if="dialogStatus == 'create'" type="primary" @click="create('form')">确 定</el-button>
                    <el-button v-else type="primary" @click="update('form')">确 定</el-button>
                </div>
            </el-dialog>

            <el-dialog title="添加角色" :visible.sync="dialogFormVisibleRole" @close="handleDialogCloseRole">

                <div style="display: flex; justify-content: center">
                    <el-transfer
                            v-model="roles"
                            :data="data"
                            :titles="['待选角色', '已选角色']"
                    ></el-transfer>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="closeRole">取 消</el-button>
                    <el-button type="primary" @click="saveRoleToUserAction">确 定</el-button>
                </div>
            </el-dialog>

            <el-dialog title="广播消息" :visible.sync="dialogNotificationVisible">
                <el-form :model="msg">
                    <el-input
                            type="textarea"
                            :autosize="{ minRows: 6, maxRows: 1}"
                            placeholder="请输入内容"
                            v-model="msg.message">
                    </el-input>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="closeRole">取 消</el-button>
                    <el-button type="primary" @click="notificationHandler">确 定</el-button>
                </div>
            </el-dialog>

        </div>
        <back-to-top></back-to-top>
    </div>
</template>

<script>
    import {created, updated, deleted, deletedBatch, selectOne, selectList, selectPage, notification} from '@/api/system/user'
    import {selectList as selectListRole} from '@/api/system/role'
    import {selectList as selectListUserRole, cudUserRole} from '@/api/system/user_role'
    import BackToTop from "@/components/BackToTop";
    import { ResultMessage } from '@/libs/response'
    import valid from '@/libs/rules'
    import { isAuth } from "@/libs/auth";

    const statusOptions = [{label: '正常', key: true}, {label: '锁定', key: false}]
    const sexOptions = [{label: '男', key: 1}, {label: '女', key: 2}, {label: '未知', key: 3}]

    export default {
        name: "user",
        components: {BackToTop},
        data() {
            let required = valid.required()
            return {
                list: null,
                total: null,
                listLoading: true,
                emptyText: '暂无数据',
                listQuery: {
                    page: 1,
                    limit: 10
                },
                form: {
                    sex: 1,
                    status: true
                },
                rules: {
                    account: [required]
                },
                multipleSelection: [],
                statusOptions,
                sexOptions,
                showAction: true,
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {update: '编辑', create: '创建'},

                dialogFormVisibleRole: false,
                data: [],
                roles: [],
                dialogNotificationVisible: false,
                msg: {
                    type: 'broadcast', 
                    mode: 'Notification', 
                    from: '0001', 
                    to: '0002', 
                    title: '系统消息', 
                    message: '系统将在【10】分钟重启，请注意保存！'
                }
            }
        },
        created() {
            this.getPage()
        },
        methods: {
            authorize(auth, rows) {
                //按钮权限验证
                return isAuth(auth)
            },
            handleAddRoleToUser(row) {//添加数据窗口
                this.userId = row.id
                this.getRoleList()
                this.dialogFormVisibleRole = true
            },
            handleDialogCloseRole() {
                this.userId = null
                this.data = []
                this.roles = []
            },
            dialogNotification() {
                this.dialogNotificationVisible = true
            },
            getRoleList() {
                selectListRole().then(response => {
                    if (response.data.status === 200) {
                        let data = []
                        for(let item of response.data.data) {
                            data.push({
                                key: item.id,
                                label: item.roleName
                            })
                        }
                        this.data = data
                    } else if(response.data.status === 601) {
                        this.$notify({
                            title: '提示', message: response.data.msg,
                            type: 'warning', duration: 2000
                        })
                    } else {
                        this.$notify({
                            title: '发生错误', message: response.data.msg,
                            type: 'error', duration: 2000
                        })
                    }
                }).then(() => {
                    this.getRoleListByUserId()
                }).catch(error => {
                })
            },
            getRoleListByUserId() {//根据用户ID查询角色
                selectListUserRole({"userId": this.userId}).then(response => {
                    if (response.data.status === 200) {
                        let roles = []
                        for(let item of response.data.data) {
                            roles.push(item.roleId)
                        }
                        this.roles = roles
                    } else if(response.data.status === 601) {
                        this.$notify({
                            title: '提示', message: response.data.msg,
                            type: 'warning', duration: 2000
                        })
                    } else {
                        this.$notify({
                            title: '发生错误', message: response.data.msg,
                            type: 'error', duration: 2000
                        })
                    }
                }).catch(error => {
                })
            },
            saveRoleToUserAction() {//获取所有角色
                const data = {"userId": this.userId, "roles": this.roles}

                cudUserRole(data).then(response => {
                    if (response.data.status === 200) {
                        this.$notify({
                            title: '提示', message: '操作成功',
                            type: 'success', duration: 2000
                        })
                    } else if(response.data.status === 601) {
                        this.$notify({
                            title: '提示', message: response.data.msg,
                            type: 'warning', duration: 2000
                        })
                    } else {
                        this.$notify({
                            title: '操作失败', message: response.da+ta.msg,
                            type: 'error', duration: 2000
                        })
                    }
                    this.dialogFormVisibleRole = false
                })
            },


            handleFilter() {//条件过滤
                this.listQuery.page = 1
                this.getPage()
            },
            handleResetFilter() {//重置过滤条件
                this.cancel('filterForm')
                this.getPage()
            },
            handleDialogClose() {//关闭窗口回调函数
                this.cancel('form')
            },
            handleSelectionChange(val) {//多选
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                this.listQuery.page = 1
                this.listQuery.limit = val
                this.getPage()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getPage()
            },
            handleCreate() {//添加数据窗口
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
            },
            handleUpdate(row) {//修改数据窗口
                this.getData(row.id).then(response => {
                    if(response) {
                        this.dialogStatus = 'update'
                        this.dialogFormVisible = true
                        this.form = Object.assign({}, response.data.data)
                    }
                })
            },
            handleDelete(row) {//批量删除数据
                let ids = []
                if (row.id != undefined) {
                    if(row.superAdmin) {
                        this.$notify({
                            title: '提示', message: '超级管理员账号不能删除',
                            type: 'warning', duration: 2000
                        })
                        return
                    } else {
                        ids.push(row.id)
                    }
                } else {
                    if (this.multipleSelection.length > 0) {
                        for (let item of this.multipleSelection) {
                            if(!item.superAdmin) {
                                ids.push(item.id)
                            }
                        }
                    }
                }
                if (ids.length <= 0) {
                    this.$notify({
                        title: '提示', message: '请选择需要删除的记录',
                        type: 'warning', duration: 2000
                    })
                } else {
                    this.$confirm('确定要删除？', '提示', {
                        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', lockScroll: true
                    }).then(() => {
                        deleted({idList: ids}).then(response => {
                            if(ResultMessage(response)) {
                                this.getPage()
                            }
                        }).catch(error => {
                            this.$notify({
                                title: '提示', message: '删除失败',
                                type: 'error', duration: 2000
                            })
                        })
                    }).catch(() => {})
                }
            },
            getData(id) { //根据ID查询数据
                this.listLoading = true
                return selectOne(id).then(response => {
                    if(ResultMessage(response, false)) {
                        this.listLoading = false
                        return response
                    } else {
                        this.listLoading = false
                        return null
                    }

                }).catch(error => {
                    this.$notify({
                        title: '提示', message: '根据ID获取数据失败',
                        type: 'error', duration: 2000
                    })
                    this.listLoading = false
                })
            },
            getPage() {//查询分页列表
                if(this.authorize('system:user:list')) {
                    this.listLoading = true
                    selectPage(this.listQuery).then(response => {
                        if(ResultMessage(response, false)) {
                            this.list = response.data.data.list
                            this.total = parseInt(response.data.data.total)
                            this.listLoading = false
                        } else {
                            this.listLoading = false
                        }
                    }).catch(error => {
                        this.listLoading = false
                        this.$notify({
                            title: '提示', message: '查询列表失败',
                            type: 'error', duration: 2000
                        })
                    })
                } else{
                    this.emptyText = '无权查看数据'
                    this.listLoading = false
                }
                
            },
            create(formName) {//添加数据
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        created(this.form).then(response => {
                            if(ResultMessage(response)) {
                                this.handleResetFilter()
                            } else {
                                this.dialogFormVisible = false
                            }
                        }).catch(error => {
                            this.$notify({
                                title: '提示', message: '添加失败',
                                type: 'error', duration: 2000
                            })
                        })
                    }
                })
            },
            update(formName) {//修改数据
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        updated(this.form).then(response => {
                            if(ResultMessage(response)) {
                                this.getPage()
                            }
                            this.dialogFormVisible = false
                        }).catch(error => {
                            this.$notify({
                                title: '提示', message: '修改失败',
                                type: 'error', duration: 2000
                            })
                        })
                    }
                })
            },
            closeRole() {
                this.dialogFormVisibleRole = false
                this.data = []
            },
            cancel(formName) {
                this.dialogFormVisible = false
                const set = this.$refs
                set[formName].resetFields()
                this.form = {
                    sex: 1,
                    status: true
                }
            },

            notificationHandler() {
                let data = {
                    "type": "broadcast", 
                    "mode": "Notification", 
                    "from": '0001', 
                    "to": '0002', 
                    "title": '系统消息', 
                    "message": '系统将在【10】分钟重启，请注意保存！'}

                notification(data).then(response => {
                    this.dialogNotificationVisible = false
                })
            }
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>

</style>